<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>视频上传中心</title>
    <style>
        .upload-container {
            max-width: 600px;
            margin: 2rem auto;
            padding: 20px;
            border: 2px dashed #ccc;
            border-radius: 8px;
            text-align: center;
        }

        #preview {
            margin-top: 1rem;
            max-width: 100%;
        }

        .progress-bar {
            height: 20px;
            background: #f0f0f0;
            border-radius: 10px;
            margin: 1rem 0;
            overflow: hidden;
        }

        .progress {
            width: 0%;
            height: 100%;
            background: #4CAF50;
            transition: width 0.3s ease;
        }

        button {
            background: #2196F3;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
        }

        button:hover {
            background: #1976D2;
        }
    </style>
</head>
<body>
<div class="upload-container">
    <h2>视频上传</h2>

    <!-- 文件选择区域 -->
    <input type="file" id="videoFile" accept="video/*" hidden>
    <button onclick="document.getElementById('videoFile').click()">选择视频文件</button>

    <!-- 文件预览 -->
    <div id="fileInfo" style="margin: 1rem 0"></div>
    <video id="preview" controls></video>

    <!-- 上传进度 -->
    <div class="progress-bar">
        <div class="progress" id="progress"></div>
    </div>

    <!-- 控制按钮 -->
    <button id="uploadBtn" disabled onclick="startUpload()">开始上传</button>
    <div id="result"></div>
</div>

<script>
    const CHUNK_SIZE = 5 * 1024 * 1024; // 分片大小5MB
    let currentFile = null;

    // 文件选择监听
    document.getElementById('videoFile').addEventListener('change', function(e) {
        const file = e.target.files[0];
        if (!file) return;

        currentFile = file;

        // 显示文件信息
        document.getElementById('fileInfo').innerHTML = `
                <p>文件名: ${file.name}</p>
                <p>文件大小: ${(file.size/1024/1024).toFixed(2)} MB</p>
            `;

        // 视频预览
        const preview = document.getElementById('preview');
        preview.src = URL.createObjectURL(file);
        preview.style.display = 'block';

        // 启用上传按钮
        document.getElementById('uploadBtn').disabled = false;
    });

    // 计算文件MD5（需要spark-md5.js）
    async function calculateFileHash(file) {
        return new Promise((resolve) => {
            const spark = new SparkMD5.ArrayBuffer();
            const reader = new FileReader();
            const chunkSize = 2 * 1024 * 1024; // 2MB采样
            const chunks = Math.ceil(file.size / chunkSize);
            let currentChunk = 0;

            reader.onload = function(e) {
                spark.append(e.target.result);
                currentChunk++;

                if (currentChunk < chunks) {
                    loadNext();
                } else {
                    resolve(spark.end());
                }
            };

            function loadNext() {
                const start = currentChunk * chunkSize;
                const end = Math.min(start + chunkSize, file.size);
                reader.readAsArrayBuffer(file.slice(start, end));
            }

            loadNext();
        });
    }

    // 执行上传
    async function startUpload() {
        if (!currentFile) return;

        const fileHash = await calculateFileHash(currentFile);
        const totalChunks = Math.ceil(currentFile.size / CHUNK_SIZE);

        // 初始化上传
        const initResponse = await fetch('/api/upload/init', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                fileName: currentFile.name,
                fileHash: fileHash,
                totalChunks: totalChunks
            })
        });

        const { uploadId } = await initResponse.json();

        // 分片上传
        for (let i = 0; i < totalChunks; i++) {
            const chunk = currentFile.slice(
                i * CHUNK_SIZE,
                Math.min((i + 1) * CHUNK_SIZE, currentFile.size)
            );

            const formData = new FormData();
            formData.append('file', chunk);
            formData.append('chunkNumber', i);
            formData.append('totalChunks', totalChunks);
            formData.append('fileHash', fileHash);
            formData.append('uploadId', uploadId);

            await fetch('/api/upload/chunk', {
                method: 'POST',
                body: formData
            });

            // 更新进度条
            const progress = ((i + 1) / totalChunks * 100).toFixed(2);
            document.getElementById('progress').style.width = `${progress}%`;
        }

        // 完成上传
        const completeResponse = await fetch('/api/upload/complete', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                fileHash: fileHash,
                uploadId: uploadId
            })
        });

        const result = await completeResponse.json();
        document.getElementById('result').innerHTML = `
                <p style="color: green;">上传成功！视频地址：${result.url}</p>
            `;
    }
</script>

<!-- 依赖库 -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/spark-md5/3.0.2/spark-md5.min.js"></script>
</body>
</html>